using System;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class AnimTextHelper : NodeHelper
    {
        public int time = 1;
        public bool animing;
        public AudioClip clip;
        private Action _cb;
        private string _s;
        private Text _Text;
        private float current;
        private float startTime;

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        protected override BindDataType bindDataType => BindDataType.Int;

        private void Update()
        {
            if (animing)
            {
                current = MathTools.clerp(0, _s.Length, (Time.time - startTime) / time);
                if (current >= _s.Length)
                {
                    current = _s.Length;
                    animing = false;
                    if (_cb != null) _cb();
                    Emit(UIEvent.End);
                }

                Text.text = _s.Substring(0, (int)current);
            }
        }

        protected override void BindData(string s)
        {
            if (_s == s) return;
            _s = s;
            startTime = Time.time;
            animing = true;
            if (clip != null) Game.single.PlayEFF(clip);
        }

        public void Set(Action cb)
        {
            _cb = cb;
        }

        public void Over()
        {
            Text.text = _s;
            animing = false;
            if (_cb != null) _cb();
        }
    }
}